package com.insta.playdroid;

import android.app.ListActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.insta.utils.HeadsetConnectionReceiver;
import com.insta.utils.SingletonPlayer;

public abstract class MediaPlayerNewListActivity extends ListActivity {

	protected IPlayer player;
	private HeadsetConnectionReceiver headsetReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/* creating and registering intent receiver */
		headsetReceiver = new HeadsetConnectionReceiver();
		registerReceiver(headsetReceiver, new IntentFilter(
				Intent.ACTION_HEADSET_PLUG));
	}

	/**
	 * Ecoute l'état des appels émis et sortants afin de gérer le player
	 */
	@SuppressWarnings("unused")
	private PhoneStateListener mPhoneListener = new PhoneStateListener()

	{
		public void onCallStateChanged(int state, String incomingNumber)

		{
			switch (state)

			{
			case TelephonyManager.CALL_STATE_RINGING:

			{
				if (SingletonPlayer.getInstancePlayer().isPlaying())
					SingletonPlayer.getInstancePlayer().pause();

				Log.v("CALL_STATE_RINGING", "Ringing");

			}

				break;

			case TelephonyManager.CALL_STATE_OFFHOOK:

			{
				if (SingletonPlayer.getInstancePlayer().isPlaying())
					SingletonPlayer.getInstancePlayer().pause();
				Log.v("CALL_STATE_OFFHOOK", "OffHook");
			}

				break;

			case TelephonyManager.CALL_STATE_IDLE:

			{
				//if (!SingletonPlayer.getInstancePlayer().isPlaying())
					//SingletonPlayer.getInstancePlayer().start();

				Log.v("CALL_STATE_IDLE", "Idle(No activity)");
			}
				break;

			default:

				Log.d("TAG", "Unknown phone state=" + state);

			}

		}

	};

	/* unregistering intent receiver */
	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(headsetReceiver);
		mPhoneListener = null;
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, 1000, 0, R.string.playing).setIcon(
				R.drawable.actual_playing_song);
		menu.add(0, 1001, 0, R.string.quit).setIcon(R.drawable.exit);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1000:

			if (player.getSong() != null) {
				player.startPlayerActivity(true);

			} else {
				Toast.makeText(this, R.string.errorNoSongSelected,
						Toast.LENGTH_SHORT).show();

			}

			break;

		case 1001:
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}